package com.ny.zmb.openapi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ny.zmb.openapi.config.YsConfig;
import com.ny.zmb.openapi.controller.entity.PersonalReportParam;
import com.ny.zmb.openapi.controller.entity.PersonalReportParamVo;
import com.ny.zmb.openapi.controller.entity.Result;
import com.ny.zmb.openapi.util.*;
import com.ny.zmb.openapi.ysutil.YsHttpUtil;
import com.ny.zmb.openapi.ysutil.base.EYinShengBase;
import com.ny.zmb.openapi.ysutil.common.ServiceEnum;
import com.ny.zmb.openapi.ysutil.common.YsPayConstant;
import com.ny.zmb.openapi.ysutil.publicInterface.QueryAmountReqCommand;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@RequestMapping("wallet")
@RestController
@CrossOrigin
public class WalletController extends EYinShengBase {

    /**
     * 请求地址域名
     */
    private static final String HTTP_NET = "https://ysgate.ysepay.com/";
    //测试 https://appdev.ysepay.com
    //生产 https://ysgate.ysepay.com
    /**
     * 发起方商户号 服务商在银盛给自己开设的商户号，即可当作发起方商户号
     * 生产环境需要使用自己的发起发商户号，并找相应的对接人员开通所需要的接口权限，并告知是国密还是RSA
     */
    private static final String CERT_ID = "826513173750017";

    private static final String ALLCHAR = "0123456789ABCDEF";

    /**
     * 银盛端公钥证书
     * 生产环境需要自行去开放平台上下载银盛公钥证书，也可以找对接人提供
     */

    private String YS_PUBLIC_CER_PATH = new YsConfig().getYsPublicCerPath();

    /**
     * 商户端私钥证书
     * 生产环境需要使用自己生产的私钥证书
     */
    private String MERC_PRIVATE_FILE = new YsConfig().getMercPrivateFile();
    /**
     * 商户端私钥证书密码
     * 生产环境需要使用自己私钥的密码
     */
    private static final String MERC_PRIVATE_FILE_PASSWORD = "197Aa2569";


    /**
     * 开通钱包上传文件
     * @param file
     * @param fileName
     * @param fileType
     * @return
     */
    @PostMapping("upload")
    public String upload(MultipartFile file,String fileName,String fileType) throws Exception{
        String HTTP_URL = HTTP_NET + "/openapi/file/report/uploadDocument";
        InputStream inputStream = file.getInputStream();
        String sha256 = DigestUtils.sha256Hex(inputStream);
        Map<String, String> metaJSONObject = new HashMap<>();
        metaJSONObject.put("sha256",sha256);
        metaJSONObject.put("fileType",fileType);
        metaJSONObject.put("fileName",fileName);
        Map<String, String> reqMap = resultMap("meta", metaJSONObject,null);
        String key = reqMap.get("resultKey");
        reqMap.remove("resultKey");
        /** 7、发送http请求获取返回结果，请求地址以文档为准*/
        try {
            //该文件上传接口必须传文件名称
            String result = HttpRequestUtil.sendPostFileAndName(HTTP_URL, reqMap, inputStream,file.getName());
            byte[] res = Base64.decodeBase64(result);
            Map<String, String> resMap = (Map<String, String>) JSONObject.parse(new String(res, "UTF-8"));
            System.out.println("http请求返回的结果为:" + JSONObject.toJSONString(resMap));

            /** 8、对结果进行解密，并使用银盛公钥验签*/
            if(StringUtils.isNotBlank(resMap.get("sign"))) {
                byte[] srcData = SignUtil.getSignDataStr1(resMap).getBytes("UTF-8");
                boolean validateSignResult= RSA256Util.validateSign(YS_PUBLIC_CER_PATH,Base64.decodeBase64(resMap.get("sign")),srcData);
                if(!validateSignResult){
                    System.out.println("验签失败");
                    throw new Exception("验签失败");
                }
            }else{
                throw new Exception("验签失败,未返回加签信息,可能是银盛未配置发起方或者发起方证书类型配置有误,返回结果提示为:{}"+resMap.get("msg"));
            }
            /** 9、针对自己的业务，根据返回的结果的code、subCode、businessData 做接入方的业务处理*/
            /** 10、使用上面生成的加密密钥key，解密返回的业务参数*/
            if (StringUtils.isNotBlank(resMap.get("businessData"))) {
                byte[] data_ = Base64.decodeBase64(resMap.get("businessData"));
                byte[] data = AESUtil.decrypt(data_, ByteUtil.hexStringToBytes(key));
                String s = new String(data, "UTF-8");
                resMap.put("businessData", s);
                System.out.println("解密后的业务参数:" + new String(data, "UTF-8"));
                return s;
            }
            System.out.println("解密后的完整参数为:" + JSONObject.toJSONString(resMap));
        } catch (Exception e) {
            System.out.println("图片上传demo失败:" + e);
        }
        throw new Exception("上传文件失败");
    }


    /**
     * 数字话钱包报备-邮政
     * @return
     */
    @PostMapping("psbc")
    public String psbc(@RequestBody PersonalReportParam param,String mercId,String riskGradeInfo) throws Exception{
        //请求接口
        String HTTP_URL = HTTP_NET + "/openapi/report/digitalRmb/psbc";
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("mercId",mercId);
        dataMap.put("riskGradeInfo",riskGradeInfo);
        Map<String,String> reqMap = resultMap("personalReportParam",param,dataMap);
        String key = reqMap.get("resultKey");
        reqMap.remove("resultKey");
        /** 7、发送http请求获取返回结果，请求地址以文档为准*/
        try {
            String result = HttpRequestUtil.getDoPostResponse(HTTP_URL, reqMap, "UTF-8", null, 20*1000);
            byte[] res = Base64.decodeBase64(result);
            Map<String, String> resMap = (Map<String, String>) JSONObject.parse(new String(res,"UTF-8"));
            System.out.println("http请求返回的结果为:"+JSONObject.toJSONString(resMap));

            /** 8、对结果进行解密，并使用银盛公钥验签*/
            if(StringUtils.isNotBlank(resMap.get("sign"))) {
                byte[] srcData = GMSignUtils.getSignDataStr1(resMap).getBytes("UTF-8");
                GMCertInfo verifyCertInfo = GMSignUtils.getVerifyCertInfo(YS_PUBLIC_CER_PATH);
                boolean validateSignResult = GMSignUtils.verifyMsgSignSM2(verifyCertInfo,Base64.decodeBase64(resMap.get("sign")),srcData);
                if(!validateSignResult){
                    System.out.println("验签失败");
                    throw new Exception("验签失败");
                }
            }else{
                System.out.println("验签失败,未返回加签信息,可能是未配置发起方或者未配置发起方的证书类型,返回结果提示为:{}"+resMap.get("msg"));
                throw new Exception("验签失败");
            }

            /** 9、针对自己的业务，根据返回的结果的code 和 subCode 做接入方的业务处理*/


            /** 10、使用上面生成的加密密钥key，解密返回的业务参数*/
            if(StringUtils.isNotBlank(resMap.get("businessData"))) {
                byte[] data_ = Base64.decodeBase64(resMap.get("businessData"));
                byte[] data = AESUtil.decrypt(data_,ByteUtil.hexStringToBytes(key));
                resMap.put("businessData", new String(data,"UTF-8"));
                System.out.println("解密后的业务参数:"+new String(data,"UTF-8"));
                return new String(data,"UTF-8");
            }
            System.out.println("解密后的完整参数为:"+JSONObject.toJSONString(resMap));
        } catch (Exception e) {
            System.out.println("商户入网申请失败:"+e.getMessage());
        }
        throw new Exception("报备失败");
    }


    /**
     * 数字话钱包报备-兴业
     * @return
     */
    @PostMapping("cib")
    public String cib(@RequestBody PersonalReportParamVo param, String mercId) throws Exception{
        //请求接口
        String HTTP_URL = HTTP_NET + "/openapi/report/digitalRmb/cib";
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("mercId",mercId);
        Map<String,String> reqMap = resultMap("personalReportParam",param,dataMap);
        String key = reqMap.get("resultKey");
        reqMap.remove("resultKey");
        /** 7、发送http请求获取返回结果，请求地址以文档为准*/
        try {
            String result = HttpRequestUtil.getDoPostResponse(HTTP_URL, reqMap, "UTF-8", null, 20*1000);
            byte[] res = Base64.decodeBase64(result);
            Map<String, String> resMap = (Map<String, String>) JSONObject.parse(new String(res,"UTF-8"));
            System.out.println("http请求返回的结果为:"+JSONObject.toJSONString(resMap));

            /** 8、对结果进行解密，并使用银盛公钥验签*/
            if(StringUtils.isNotBlank(resMap.get("sign"))) {
                byte[] srcData = GMSignUtils.getSignDataStr1(resMap).getBytes("UTF-8");
                GMCertInfo verifyCertInfo = GMSignUtils.getVerifyCertInfo(YS_PUBLIC_CER_PATH);
                boolean validateSignResult = GMSignUtils.verifyMsgSignSM2(verifyCertInfo,Base64.decodeBase64(resMap.get("sign")),srcData);
                if(!validateSignResult){
                    System.out.println("验签失败");
                    throw new Exception("验签失败");
                }
            }else{
                System.out.println("验签失败,未返回加签信息,可能是未配置发起方或者未配置发起方的证书类型,返回结果提示为:{}"+resMap.get("msg"));
                throw new Exception("验签失败");
            }

            /** 9、针对自己的业务，根据返回的结果的code 和 subCode 做接入方的业务处理*/


            /** 10、使用上面生成的加密密钥key，解密返回的业务参数*/
            if(StringUtils.isNotBlank(resMap.get("businessData"))) {
                byte[] data_ = Base64.decodeBase64(resMap.get("businessData"));
                byte[] data = AESUtil.decrypt(data_,ByteUtil.hexStringToBytes(key));
                resMap.put("businessData", new String(data,"UTF-8"));
                System.out.println("解密后的业务参数:"+new String(data,"UTF-8"));
                return new String(data,"UTF-8");
            }
            System.out.println("解密后的完整参数为:"+JSONObject.toJSONString(resMap));
        } catch (Exception e) {
            System.out.println("商户入网申请失败:"+e.getMessage());
        }
        throw new Exception("报备失败");
    }

    /**
     * 数字人民币报备撤销API
     * @return
     */
    @RequestMapping("revoke")
    public String revoke(String reportChannel, String mercId) throws Exception{
        //请求接口
        String HTTP_URL = HTTP_NET + "/openapi/report/digitalRmb/revoke";
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("mercId",mercId);
        Map<String,String> reqMap = resultMap("reportChannel",reportChannel,dataMap);
        String key = reqMap.get("resultKey");
        reqMap.remove("resultKey");
        /** 7、发送http请求获取返回结果，请求地址以文档为准*/
        try {
            String result = HttpRequestUtil.getDoPostResponse(HTTP_URL, reqMap, "UTF-8", null, 20*1000);
            byte[] res = Base64.decodeBase64(result);
            Map<String, String> resMap = (Map<String, String>) JSONObject.parse(new String(res,"UTF-8"));
            System.out.println("http请求返回的结果为:"+JSONObject.toJSONString(resMap));

            /** 8、对结果进行解密，并使用银盛公钥验签*/
            if(StringUtils.isNotBlank(resMap.get("sign"))) {
                byte[] srcData = GMSignUtils.getSignDataStr1(resMap).getBytes("UTF-8");
                GMCertInfo verifyCertInfo = GMSignUtils.getVerifyCertInfo(YS_PUBLIC_CER_PATH);
                boolean validateSignResult = GMSignUtils.verifyMsgSignSM2(verifyCertInfo,Base64.decodeBase64(resMap.get("sign")),srcData);
                if(!validateSignResult){
                    System.out.println("验签失败");
                    throw new Exception("验签失败");
                }
            }else{
                System.out.println("验签失败,未返回加签信息,可能是未配置发起方或者未配置发起方的证书类型,返回结果提示为:{}"+resMap.get("msg"));
                throw new Exception("验签失败");
            }

            /** 9、针对自己的业务，根据返回的结果的code 和 subCode 做接入方的业务处理*/


            /** 10、使用上面生成的加密密钥key，解密返回的业务参数*/
            if(StringUtils.isNotBlank(resMap.get("businessData"))) {
                byte[] data_ = Base64.decodeBase64(resMap.get("businessData"));
                byte[] data = AESUtil.decrypt(data_,ByteUtil.hexStringToBytes(key));
                resMap.put("businessData", new String(data,"UTF-8"));
                System.out.println("解密后的业务参数:"+new String(data,"UTF-8"));
                return new String(data,"UTF-8");
            }
            System.out.println("解密后的完整参数为:"+JSONObject.toJSONString(resMap));
        } catch (Exception e) {
            System.out.println("商户入网申请失败:"+e.getMessage());
        }
        throw new Exception("报备失败");
    }

    /**
     * 数字人民币报备查询API
     * @return
     */
    @RequestMapping("search")
    public String search(String reportChannel, String mercId) throws Exception{
        //请求接口
        String HTTP_URL = HTTP_NET + "/openapi/report/digitalRmb/search";
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("mercId",mercId);
        Map<String,String> reqMap = resultMap("reportChannel",reportChannel,dataMap);
        String key = reqMap.get("resultKey");
        reqMap.remove("resultKey");
        /** 7、发送http请求获取返回结果，请求地址以文档为准*/
        try {
            String result = HttpRequestUtil.getDoPostResponse(HTTP_URL, reqMap, "UTF-8", null, 20*1000);
            byte[] res = Base64.decodeBase64(result);
            Map<String, String> resMap = (Map<String, String>) JSONObject.parse(new String(res,"UTF-8"));
            System.out.println("http请求返回的结果为:"+JSONObject.toJSONString(resMap));

            /** 8、对结果进行解密，并使用银盛公钥验签*/
            if(StringUtils.isNotBlank(resMap.get("sign"))) {
                byte[] srcData = GMSignUtils.getSignDataStr1(resMap).getBytes("UTF-8");
                GMCertInfo verifyCertInfo = GMSignUtils.getVerifyCertInfo(YS_PUBLIC_CER_PATH);
                boolean validateSignResult = GMSignUtils.verifyMsgSignSM2(verifyCertInfo,Base64.decodeBase64(resMap.get("sign")),srcData);
                if(!validateSignResult){
                    System.out.println("验签失败");
                    throw new Exception("验签失败");
                }
            }else{
                System.out.println("验签失败,未返回加签信息,可能是未配置发起方或者未配置发起方的证书类型,返回结果提示为:{}"+resMap.get("msg"));
                throw new Exception("验签失败");
            }

            /** 9、针对自己的业务，根据返回的结果的code 和 subCode 做接入方的业务处理*/


            /** 10、使用上面生成的加密密钥key，解密返回的业务参数*/
            if(StringUtils.isNotBlank(resMap.get("businessData"))) {
                byte[] data_ = Base64.decodeBase64(resMap.get("businessData"));
                byte[] data = AESUtil.decrypt(data_,ByteUtil.hexStringToBytes(key));
                resMap.put("businessData", new String(data,"UTF-8"));
                System.out.println("解密后的业务参数:"+new String(data,"UTF-8"));
                return new String(data,"UTF-8");
            }
            System.out.println("解密后的完整参数为:"+JSONObject.toJSONString(resMap));
        } catch (Exception e) {
            System.out.println("商户入网申请失败:"+e.getMessage());
        }
        throw new Exception("报备失败");
    }


    /**
     * 查询钱包余额
     */
    @GetMapping("checkWallet")
    public Result checkWallet(String mercId) throws Exception{
        if (StringUtils.isBlank(mercId)){
            return Result.fail("前填写商户号");
        }
        String httpUrl = HTTP_NET+"/openapi/unify/merchant/balance/query";
        Map<String,String> reqMap = resultMap("mercId",mercId,null);
        String key = reqMap.get("resultKey");
        reqMap.remove("resultKey");
        /** 7、发送http请求获取返回结果，请求地址以文档为准*/
        try {
            String result = HttpRequestUtil.getDoPostResponse(httpUrl, reqMap, "UTF-8", null, 20*1000);
            byte[] res = Base64.decodeBase64(result);
            Map<String, String> resMap = (Map<String, String>) JSONObject.parse(new String(res,"UTF-8"));
            System.out.println("http请求返回的结果为:"+JSONObject.toJSONString(resMap));

            /** 8、对结果进行解密，并使用银盛公钥验签*/
            if(StringUtils.isNotBlank(resMap.get("sign"))) {
                byte[] srcData = GMSignUtils.getSignDataStr1(resMap).getBytes("UTF-8");
                GMCertInfo verifyCertInfo = GMSignUtils.getVerifyCertInfo(YS_PUBLIC_CER_PATH);
                boolean validateSignResult = GMSignUtils.verifyMsgSignSM2(verifyCertInfo,Base64.decodeBase64(resMap.get("sign")),srcData);
                if(!validateSignResult){
                    System.out.println("验签失败");
                    return Result.fail("查询失败");
                }
            }else{
                System.out.println("验签失败,未返回加签信息,可能是未配置发起方或者未配置发起方的证书类型,返回结果提示为:{}"+resMap.get("msg"));
                return Result.fail("查询失败");
            }

            /** 9、针对自己的业务，根据返回的结果的code 和 subCode 做接入方的业务处理*/
            /** 10、使用上面生成的加密密钥key，解密返回的业务参数*/
            if(StringUtils.isNotBlank(resMap.get("businessData"))) {
                byte[] data_ = Base64.decodeBase64(resMap.get("businessData"));
                byte[] data = AESUtil.decrypt(data_,ByteUtil.hexStringToBytes(key));
                String s = new String(data, "UTF-8");
                resMap.put("businessData", s);
                System.out.println("解密后的业务参数:"+new String(data,"UTF-8"));
                return Result.ok(JSONObject.parseObject(s));
            }
            return Result.fail("查询失败");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("查询失败");
        }
    }
    /**
     * 格式化当前日期时间字符串
     * @return
     */
    private static  String getCurrentDateTime(String pattern){
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(new Date());
    }

    private Map<String,String> resultMap(String keyValue,Object value,Map<String,Object> addMap) throws Exception{
        /** 1、封装请求参数，bizContent（业务参数，需要加密）和chec（需要生成密钥并加密）后面设置值*/
        Map<String,String> reqMap = new HashMap<String,String>();
        reqMap.put("method", "openapi.unify.merchant.balance.query");
        reqMap.put("timeStamp",getCurrentDateTime("yyyy-MM-dd HH:mm:dd"));
        reqMap.put("charset","utf-8");
        reqMap.put("reqId",String.valueOf(System.currentTimeMillis()));
        reqMap.put("certId",CERT_ID);//测试环境可以用这个
        reqMap.put("version","1.0");

        /** 2、生成对业务参数加密的密钥*/
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 16; i++) {
            sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length())));
        }
        String key = ByteUtil.toHexString(sb.toString());

        /** 3、使用银盛公钥对密钥key进行加密，得到加密的key并设置到请求参数check中。publicFilePath为存放银盛公钥的地址*/
        String check = GMSignUtils.encryptData(YS_PUBLIC_CER_PATH,key);
        reqMap.put("check",check);//加密后的密钥

        /** 4、封装业务参数,具体参数见文档，这里只是举例子*/
        Map<String,Object> bizContentMap = new HashMap<>();
        //商户号，此商户号一定要是该发起发下的商户号
        bizContentMap.put(keyValue,value);
        if (null != addMap){
            bizContentMap.putAll(addMap);
        }

        /** 5、使用生成的密钥key对业务参数进行加密，并将加密后的业务参数放入请求参数bizContent中*/
        JSONObject bizJSONObj = JSONObject.parseObject(JSON.toJSONString(bizContentMap));
        byte[] bte= AESUtil.encrypt(JSONObject.toJSONBytes(bizJSONObj, SerializerFeature.WriteNullStringAsEmpty), ByteUtil.hexStringToBytes(key));
        String msgBizConten = Base64.encodeBase64String(bte);
        reqMap.put("bizContent",msgBizConten);

        /** 6、将请求参数进行sort排序，生成拼接的字符床，并使用接入方私钥对请求参数进行加签，并将加签的值存入请求参数sign中*/
        //6.1 排序生成拼接字符串
        List<String> keys = new ArrayList<String>(reqMap.keySet());
        Collections.sort(keys);
        StringBuilder sb1 = new StringBuilder();
        for(String k : keys){
            if("sign".equals(k)) {
                continue;
            }
            sb1.append(k).append("=");
            sb1.append(reqMap.get(k));
            sb1.append("&");
        }
        if(sb1.length() > 0) {
            sb1.setLength(sb1.length() - 1);
        }
        //6.2使用接入方私钥对排序的请求参数加签，并存放到请求参数里面.privateFilePath:私钥地址，prvatePassword:私钥密钥
        String sign = GMSignUtils.signMsgSM2(MERC_PRIVATE_FILE,MERC_PRIVATE_FILE_PASSWORD, sb1.toString());
        reqMap.put("sign",sign );
        reqMap.put("resultKey",key);
        return reqMap;
    }
}
